<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="当事人名称" prop="partyName">
        <el-input
          v-model="queryParams.partyName"
          placeholder="请输入当事人名称"
          clearable
          :style="{ width: '220px' }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="处罚决定书文号" prop="decisionsNo" class="long-label">
        <el-input
          v-model="queryParams.decisionsNo"
          placeholder="请输入行政处罚决定书文号"
          clearable
          :style="{ width: '220px' }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="登记时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :style="{ width: '220px' }"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['penaltydeferralresult:penaltydeferralresult:add']">
          新增
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['penaltydeferralresult:penaltydeferralresult:edit']">
          修改
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['penaltydeferralresult:penaltydeferralresult:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          :disabled="multiple"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['penaltydeferralresult:penaltydeferralresult:export']">
          导出
        </el-button>
        <el-button type="warning" :disabled="multiple" plain icon="Download" @click="handleExport2">
          导出送达回证
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="penaltydeferralresultList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="column in newColumns" :key="column.key">
        <el-table-column
          :label="column.label"
          :prop="column.key"
          :min-width="column.minWidth || ''"
          :width="column.width || ''">
          <template #default="scope" v-if="column.key === 'createTime'">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </template>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="240"
        :show-overflow-tooltip="false"
        fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="view"
            @click="handleUpdate(scope.row, 'view')"
            v-hasPermi="['penaltydeferralresult:penaltydeferralresult:query']">
            查看
          </el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row, 'edit')"
            v-hasPermi="['penaltydeferralresult:penaltydeferralresult:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="view" @click="handlePreview(scope.row)">预览</el-button>
          <el-button link type="primary" icon="upload" @click="handleUpload(scope.row)">上传附件</el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['penaltydeferralresult:penaltydeferralresult:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改分期(延期)缴纳罚款决定书对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form
        ref="penaltydeferralresultRef"
        :model="form"
        :rules="rules"
        :disabled="title === '查看分期(延期)缴纳罚款决定书'"
        label-width="138px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="立案号" prop="caseId">
              <el-select
                v-model="form.caseId"
                :disabled="pageType !== 'add'"
                placeholder="请选择立案号"
                clearable
                @change="handleCase">
                <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当事人名称" prop="partyName">
              <el-input v-model="form.partyName" disabled placeholder="请输入当事人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-model="form.creditCode" disabled placeholder="请输入统一社会信用代码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法定代表人" prop="legalRepresentative">
              <el-input v-model="form.legalRepresentative" disabled placeholder="请输入法定代表人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号码" prop="idNumber">
              <el-input v-model="form.idNumber" disabled placeholder="请输入身份证号码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="处罚决定书文号" prop="decisionsNo">
              <el-input v-model="form.decisionsNo" disabled placeholder="请输入行政处罚决定书文号" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="地址" prop="addressObj">
              <locationSelect v-model="form.addressObj" disabled style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="送达日期" prop="deliveryDate">
              <el-date-picker
                v-model="form.deliveryDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择送达日期" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="penaltyAmount" label="罚款金额">
              <el-input-number
                v-model="form.penaltyAmount"
                :min="0"
                controls-position="right"
                align="left"
                placeholder="请输入处罚金额"
                disabled
                style="width: calc(100% - 40px); margin-right: 5px" />
              元整
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="70px">
              <span style="font-weight: bold; font-size: 16px">
                {{
                  form.isAgree === '1'
                    ? `同意${form.type === '1' ? '分期' : '延期'}缴纳罚款事项`
                    : `不予${form.type === '1' ? '分期' : '延期'}缴纳罚款事项`
                }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请日期" prop="applyDate">
              <el-date-picker v-model="form.applyDate" disabled type="date" placeholder="请选择申请日期" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="reason" label="申请理由">
              <el-input v-model="form.reason" disabled placeholder="请输入申请理由" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.isAgree === '2'" :span="24">
            <el-form-item prop="handlerOpinion" label="不予理由">
              <el-input
                type="textarea"
                :rows="4"
                v-model="form.handlerOpinion"
                disabled
                placeholder="请输入不予理由"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.isAgree === '1'" :span="24">
            <el-form-item label="法规依据" prop="content">
              <el-input
                type="textarea"
                :rows="4"
                v-model="form.content"
                disabled
                placeholder="请输入法规依据"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">提 交</el-button>
          <el-button :loading="preViewLoading" @click="handlePreview2">预览</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传附件弹窗 -->
    <el-dialog title="上传附件" v-model="fileModal" width="1200px">
      <FileList v-if="fileModal" :fileUploadList="fileUploadList" />
      <template #footer>
        <div class="form-footer">
          <el-button type="primary" @click="handleUploadConfirm">保存</el-button>
          <el-button @click="() => (fileModal = false)">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Penaltydeferralresult">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import {
  listPenaltydeferralresult,
  getPenaltydeferralresult,
  delPenaltydeferralresult,
  addPenaltydeferralresult,
  updatePenaltydeferralresult,
  exportPenaltydeferralresult,
  previewPenaltydeferralresult,
  getCaseList,
  getDecisionsList,
  exportPenaltydeferralresultReceipt,
  addNoticedemandapprovalFiles,
  previewInquiryPdf,
} from '@/api/decisionl/index.js'
import { registrationcaseDetail } from '@/api/filingReview/register'
import { downloadBlob } from '@/utils/download.js'
import { ElMessage } from 'element-plus'
import FileList from '@/components/FileList/index.vue'
import locationSelect from '@/components/locationSelect/index.vue'

const { proxy } = getCurrentInstance()
const route = useRoute()

const query = route.query
if (query.formId) {
  // 案件检索跳转过来
  proxy.$nextTick(() => {
    setTimeout(() => {
      handleUpdate({ id: query.formId }, 'view')
    }, 100)
  })
}

const penaltydeferralresultList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedTPenaltyDeferralResultFiles = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const daterangeCreateTime = ref([])

const columns = ref([
  { key: 'deferralNo', label: '缴纳罚款决定书文号', visible: true, minWidth: '260' },
  { key: 'name', label: '文书名称', visible: true, minWidth: '240' },
  { key: 'partyName', label: '当事人名称', visible: true, minWidth: '180' },
  { key: 'caseCause', label: '案由', visible: true, minWidth: '220' },
  { key: 'createTime', label: '登记时间', visible: true, width: '160' },
])
const newColumns = computed(() => {
  return columns.value.filter(column => column.visible)
})
// 案件列表
const numberList = ref([])

// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule, value, callback) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择拍摄地点'))
  } else {
    callback()
  }
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    decisionsNo: null,
    partyName: null,
    createTime: null,
  },
  rules: {
    caseId: [{ required: true, message: '立案登记ID不能为空', trigger: ['blur', 'change'] }],
    caseNo: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
    caseCause: [{ required: true, message: '案由不能为空', trigger: ['blur', 'change'] }],
    decisionsNo: [{ required: true, message: '行政处罚决定书文号不能为空', trigger: ['blur', 'change'] }],
    partyId: [{ required: true, message: '当事人Id不能为空', trigger: ['blur', 'change'] }],
    partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
    creditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: ['blur', 'change'] }],
    legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
    idNumber: [{ required: true, message: '身份证号码不能为空', trigger: ['blur', 'change'] }],
    addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
    content: [{ required: true, message: '法规依据不能为空', trigger: ['blur', 'change'] }],
    deliveryDate: [{ required: true, message: '送达日期不能为空', trigger: ['blur', 'change'] }],
  },
})

const { queryParams, form, rules } = toRefs(data)

// 获取案件列表
const handleCaseList = async () => {
  try {
    const res = await getCaseList()
    numberList.value = res.data.map(item => ({
      label: item.caseNo,
      value: item.id,
    }))
  } catch (error) {
    console.error('获取案件列表失败:', error)
  }
}
// 处理案件选择变化
const handleCase = async val => {
  if (!val) {
    form.value = {
      partyName: '',
      legalRepresentative: '',
      creditCode: '',
      addressObj: {
        photoLocation: '',
        streetOfPhotoLocation: '',
      },
    }
    return
  }

  try {
    const res = await registrationcaseDetail(val)
    const res2 = await getDecisionsList({ caseId: val })
    const {
      partyName,
      partyId,
      legalRepresentative,
      unifiedSocialCreditCode,
      streetOfCompanyAddress,
      address,
      idNumber,
    } = res.data
    form.value = {
      ...form.value,
      caseNo: numberList.value.find(item => item.value === val)?.label || '',
      decisionsId: res2.data.id,
      decisionsNo: res2.data.decisionsNo,
      partyId: partyId,
      partyName: partyName,
      legalRepresentative: legalRepresentative,
      creditCode: unifiedSocialCreditCode,
      idNumber,
      addressObj: {
        photoLocation: address,
        streetOfPhotoLocation: streetOfCompanyAddress,
      },
      penaltyAmount: res2.data.penaltyAmount,
      applyDate: res2.data.applyDate,
      reason: res2.data.reason,
      handlerOpinion: res2.data.handlerOpinion,
      content: res2.data.content,
      isAgree: res2.data.isAgree,
      penaltyDeferralId: res2.data.penaltyDeferralId,
    }
  } catch (error) {
    console.error('获取案件详情失败:', error)
  }
}

/** 查询分期(延期)缴纳罚款决定书列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params['beginCreateTime'] = daterangeCreateTime.value[0]
    queryParams.value.params['endCreateTime'] = daterangeCreateTime.value[1]
  }
  listPenaltydeferralresult(queryParams.value).then(response => {
    penaltydeferralresultList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    isAgree: null,
    deferralYear: null,
    deferralSerialNo: null,
    deferralNo: null,
    caseId: null,
    caseNo: null,
    caseCause: null,
    decisionsNo: null,
    partyId: null,
    partyName: null,
    creditCode: null,
    legalRepresentative: null,
    content: null,
    createTime: null,
    updateTime: null,
    delFlag: null,
  }
  proxy.resetForm('penaltydeferralresultRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const pageType = ref('add')
function handleAdd() {
  reset()
  open.value = true
  pageType.value = 'add'
  title.value = '添加分期(延期)缴纳罚款决定书'
  handleCaseList()
}

/** 修改按钮操作 */
function handleUpdate(row, type) {
  reset()
  pageType.value = 'edit'
  const _id = row.id || ids.value
  getPenaltydeferralresult(_id).then(res => {
    // 处理地址数据格式
    if (res.data.address || res.data.streetOfCompanyAddress) {
      res.data.addressObj = {
        photoLocation: res.data.address || '',
        streetOfPhotoLocation: res.data.streetOfCompanyAddress || '',
      }
    }
    res.data.handlerOpinion = res.data.content
    form.value = res.data
    open.value = true
    title.value = (type === 'edit' ? '修改' : '查看') + '分期(延期)缴纳罚款决定书'
    handleCaseList()
  })
}

// 预览
const previewRow = ref(null)
const handlePreview = async row => {
  loading.value = true
  previewRow.value = row
  const res = await previewPenaltydeferralresult(row.id)
  if (!!res.msg) {
    window.open(res.msg)
  } else {
    ElMessage.warning('预览文件不存在')
  }
  loading.value = false
}
// 上传附件
const fileModal = ref(false)
const fileUploadList = ref([])
const rowId = ref('')
const handleUpload = async row => {
  rowId.value = row.id
  const res = await getPenaltydeferralresult(row.id)
  fileUploadList.value = res.data.tpenaltyDeferralResultFilesList || []
  fileModal.value = true
}

// 上传附件
const handleUploadConfirm = async () => {
  await addNoticedemandapprovalFiles({ id: rowId.value, tpenaltyDeferralResultFilesList: fileUploadList.value })
  ElMessage.success('保存成功')
  fileModal.value = false
}

/** 预览 */
const preViewLoading = ref(false)
const handlePreview2 = () => {
  preViewLoading.value = true
  submitForm(true)
    .then(async params => {
      const res = await previewInquiryPdf(params)
      if (!!res.msg) {
        window.open(res.msg)
      } else {
        ElMessage.warning('预览文件不存在')
      }
      preViewLoading.value = false
    })
    .catch(() => {
      preViewLoading.value = false
    })
}

/** 提交按钮 */
function submitForm(isPreview = false) {
  return new Promise((resolve, reject) => {
    proxy.$refs['penaltydeferralresultRef'].validate(valid => {
      if (valid) {
        console.log('submit!', form.value)
        // 处理地址数据
        const submitData = {
          id: form.value.id,
          penaltyDeferralId: form.value.penaltyDeferralId,
          deliveryDate: form.value.deliveryDate,
          content: form.value.isAgree === '2' ? form.value.handlerOpinion : form.value.content,
          address: form.value.addressObj.photoLocation,
          streetOfCompanyAddress: form.value.addressObj.streetOfPhotoLocation,
        }
        if (isPreview === true) {
          resolve(submitData)
          return
        }
        if (form.value.id != null) {
          updatePenaltydeferralresult(submitData).then(response => {
            proxy.$modal.msgSuccess('修改成功')
            open.value = false
            getList()
          })
        } else {
          addPenaltydeferralresult(submitData).then(response => {
            proxy.$modal.msgSuccess('新增成功')
            open.value = false
            getList()
          })
        }
      } else {
        reject()
      }
    })
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确定删除分期(延期)缴纳罚款决定书编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delPenaltydeferralresult(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
async function handleExport() {
  const _ids = ids.value
  const res = await exportPenaltydeferralresult(_ids)
  downloadBlob(res)
}

// 导出送达回证
async function handleExport2() {
  const _ids = ids.value
  const res = await exportPenaltydeferralresultReceipt(_ids)
  downloadBlob(res)
}
getList()
</script>
